'use strict'
import React from "react";
import {render} from 'react-dom';
import {Link} from 'react-router';
//引入工具类
import MMALL_COM from 'util/comm.jsx';
import PRUDUCT from 'service/product_service.jsx';
import FileUploader from 'page/component/file-upload/index.jsx';
import RichEditor   from 'page/component/rich-editor/index.jsx';
//引入依赖页面
import PageTitle from 'page/component/page-title/index.jsx';

//引入样式文件
import './save.scss';

const _comm    = new MMALL_COM();
const _product = new PRUDUCT();
class ProductSave extends React.Component{
    constructor(props){
        super(props);
        this.state={
            id                 :this.props.params.id,
            name               : '',
            subtitle           : '',
            price              : 10000,
            stock              : 10000, 
            firstCategoryList  : [],
            firstCategoryId    : '',
            secondCategoryList : [],
            subImages          : [],
            detail             : '' 
        }
        //绑定this
        this.getCateOne     =    this.getCateOne.bind(this);
        this.getCateTwo     =    this.getCateTwo.bind(this);
        this.onChangeInput  =    this.onChangeInput.bind(this);
        this.onUploadSuccess=    this.onUploadSuccess.bind(this);
        this.onUploadError  =    this.onUploadError.bind(this);
    }
    componentDidMount(){
        this.getProduct();
        this.getCateOne();
    }
    //得到商品信息
    getProduct(){
        //如果有id字段
        if(this.state.id){
            let id=this.state.id;
            _product.getProduct(id).then(res=>{
                let product=this.productAdapter(res);

                this.setState(product);
                if(product.firstCategoryId){
                    this.getCateTwo();
                }
                this.refs['rich-editor'].setValue(product.detail);
            },
            msg=>{
                _comm.errorTip('出错了，请稍后再试');
            })
        }
    }
    // 适配接口返回的数据
    productAdapter(product){
        // 如果父品类是0（根品类），则categoryId作为一级品类
        let firstCategoryId     = product.parentCategoryId === 0 ? product.categoryId : product.parentCategoryId,
            secondCategoryId    = product.parentCategoryId === 0 ? '' : product.categoryId;
        return {
            categoryId          : product.categoryId,
            name                : product.name,
            subtitle            : product.subtitle,
            subImages           : product.subImages.split(','),
            detail              : product.detail,
            price               : product.price,
            stock               : product.stock,
            firstCategoryId     : firstCategoryId,
            secondCategoryId    : secondCategoryId,
            status              : product.status,
            nameNotNull         : !!product.name,
            cateNotNull         : !product.firstCategoryId,
            subtitleNotNull     : !!product.subtitle,
        }
    }
    //获取一级分类
    getCateOne(){
        _product.getCategory().then(res=>{
            this.setState({firstCategoryList:res});
        },
        msg=>{
            _comm.errorTip(msg);
        })
    }
    //获取二级分类
    getCateTwo(){
        if(!this.state.firstCategoryId)
            return;

        _product.getCategory(this.state.firstCategoryId).then(res=>{
            this.setState({secondCategoryList:res})
        },
        msg=>{
             _comm.errorTip(msg);
        })
    }
    //一级分类改变事件
    onChangeCateOne(e){
        this.setState({
            firstCategoryId     : e.target.value,
            secondCategoryId    : 0,
            secondCategoryList  : [],
            cateNotNull         : !!e.target.value
        },()=>this.getCateTwo())
    }
    //二级分类改变
    onChangeCateTwo(e){
        this.setState({
            secondCategoryId:e.target.value,
        })        
    }
    //输入表单的值发生变化
    onChangeInput(e){
        let name  = e.target.name,
            value = e.target.value;
        this.setState({
            [name]:value
        },()=>this.checkForm())
    }
    //上传图片成功
    onUploadSuccess(res){
        let imgList = this.state.subImages;
        imgList.push(res.data.uri);
        this.setState({
            subImages:imgList
        })
    }
    //上传图片失败
    onUploadError(res){
        _comm.errorTip('上传图片失败')
    }
    //删除上传的图片
    onDeleteImage(img){
        let imgList = this.state.subImages;
        let index   = imgList.indexOf(img);
        index>=0?imgList.splice(index,1):null;
        this.setState({
            subImages:imgList
        })

    }
    //富文本文字变化
    onChangeRichEditor(detail){
        this.setState(
        {
            detail:detail
        })
    }
    //验证表单元素
    checkForm(){
        let nameNotNull=!!this.state.name,
            subtitleNotNull=!!this.state.subtitle;
        this.setState({
            nameNotNull:nameNotNull,
            subtitleNotNull:subtitleNotNull,
        })
        return this.state.nameNotNull&&this.state.cateNotNull&&this.state.subtitleNotNull?  true :  false;
    }
    //表单提交
    onSubmit(){
        if(this.checkForm()){
            let product={
                name:this.state.name,
                categoryId:this.state.secondCategoryId||this.state.firstCategoryId||0,
                subtitle:this.state.subtitle,
                subImages:this.state.subImages.join(','),
                detail:this.state.detail,
                price:this.state.price,
                stock:this.state.stock,
                status:this.state.status||1
            }
            //如果存在id字段，需要加入id参数**编辑**
            if(this.state.id){
                product.id=this.state.id;
            }
            _product.saveProduct(product).then(res=>{
                _comm.successTip(res);
                window.location.href="#/product/index";
            },
            msg=>{
                _comm.errorTip(msg);
            })
        }
    }
    //加载商品列表
    render(){
        return (
            <div id="page-wrapper">
                <PageTitle pageTitle={'商品管理 -- ' + (this.state.id ? '修改商品' : '添加商品')}/>
                <div className="row">
                       <div className="form-wrap col-lg-12">
                            <div className="form-box form-horizontal">
                                <div className="form-label form-group">
                                    <label htmlFor='name' className='col-md-2 control-label'>商品名称</label>
                                    <div className="col-md-5">
                                        <input  type="text"  id="name" placeholder='请输入商品名称' className='form-control' 
                                        name='name' value={this.state.name} onChange={this.onChangeInput} />
                                    </div>
                                    {
                                        !this.state.nameNotNull?
                                    <div className='error-tip col-md-5'>**请输入商品名称</div>:''
                                    }
                                </div>
                                <div className="form-label form-group">
                                    <label htmlFor='subtitle' className='col-md-2 control-label'>商品描述</label>
                                    <div className="col-md-5">
                                        <input  type="text" id="subtitle" placeholder='请输入商品描述' className='form-control'
                                        name="subtitle" value={this.state.subtitle} onChange={this.onChangeInput} />
                                    </div>
                                    {
                                        !this.state.subtitleNotNull?
                                    <div className='error-tip col-md-5'>**请输入商品描述</div>:''
                                    }
                                </div>
                                <div className="form-label form-group">
                                    <label htmlFor='subtitle' className='col-md-2 control-label'>所属分类</label>
                                    <div className="col-md-5">
                                        <select className='form-control cate-select col-md-5' onChange={this.onChangeCateOne.bind(this)} value={this.state.firstCategoryId}>
                                            <option value=''>
                                                选择所属一级分类
                                            </option>
                                            {
                                                this.state.firstCategoryList.map((category, index) => {
                                                    return (
                                                        <option value={category.id} key={index} >{category.name}</option>
                                                    );
                                                })
                                            }
                                        </select>
                                        {
                                            this.state.secondCategoryList.length?
                                            <select className='form-control cate-select col-md-5' onChange={this.onChangeCateTwo.bind(this)} value={this.state.secondCategoryId}>
                                                <option value=''>
                                                    选择所属二级分类
                                                </option>
                                                {
                                                    this.state.secondCategoryList.map((category, index) => {
                                                        return (
                                                            <option value={category.id} key={index}>{category.name}</option>
                                                        );
                                                    })
                                                }
                                            </select>:''
                                        }
                                    </div>
                                    {
                                        !this.state.cateNotNull?
                                        <div className='error-tip col-md-5'>**请选择商品分类</div>:''
                                    }
                                </div>
                                <div className="form-label form-group">
                                    <label htmlFor='price' className='col-md-2 control-label'>商品价格</label>
                                    <div className="col-md-3">
                                        <div className="input-group">
                                            <input type="number" id="price" placeholder='请输入商品价格' className='form-control'
                                            name="price" value={this.state.price} onChange={this.onChangeInput} />
                                            <div className="input-group-addon">元</div>
                                        </div>
                                    </div>
                                </div>
                                <div className="form-label form-group">
                                    <label htmlFor='stock' className='col-md-2 control-label'>商品库存</label>
                                    <div className="col-md-3">
                                        <div className="input-group">
                                            <input  type="number" id="stock" placeholder='请输入库存' className='form-control' 
                                            name="stock" value={this.state.stock} onChange={this.onChangeInput} />
                                            <div className="input-group-addon">件</div>
                                        </div>
                                    </div>
                                </div>
                                <div className="form-label form-group">
                                    <label htmlFor='img' className='col-md-2 control-label'>商品图片</label>
                                    <div className="img-con col-md-10">
                                        {
                                            this.state.subImages.length ? this.state.subImages.map((image, index) => {
                                                return (
                                                    <div className="sub-img" key={index}>
                                                        <img className="img" src={_comm.getImageUrl(image)}/>
                                                        <i className="fa fa-close fa-fw" onClick={this.onDeleteImage.bind(this, image)}></i>
                                                    </div>
                                                );
                                            }) : <div className="notice">请上传图片</div>
                                        }
                                    </div>
                                    <div className="col-md-offset-2 col-md-10">
                                        <FileUploader onSuccess={this.onUploadSuccess} onError={this.onUploadError} />
                                    </div>
                                </div>
                                <div className="form-label form-group">
                                    <label htmlFor='img' className='col-md-2 control-label'>商品详情</label>
                                    <div className="col-md-10">
                                        <RichEditor ref='rich-editor' onValueChange={this.onChangeRichEditor.bind(this)} placeholder="商品详细信息" value={this.state.detail}/>
                                    </div>

                                </div>
                                <div className="form-group">
                                    <div className="col-md-offset-2 col-md-10">
                                        <button type="btn" className="btn btn-xl btn-primary" onClick={this.onSubmit.bind(this)}>提交</button>
                                    </div>
                                </div>
                            </div>
                       </div>
                </div>
            </div>
        )
    }
}
export default ProductSave;
